from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from src.infrastructure.config import config
import logging

logger = logging.getLogger(__name__)

def DatabaseManager():
    """创建数据库URL"""
    db_config = config.get_value('database', {})
    
    # 确保所有必要的配置都存在且有效
    required_fields = ['type', 'host', 'port', 'username', 'password', 'database']
    for field in required_fields:
        if not db_config.get(field):
            raise ValueError(f"Missing required database configuration: {field}")
    
    # 确保端口是整数
    try:
        port = int(db_config['port'])
    except (ValueError, TypeError):
        logger.warning(f"Invalid port number: {db_config['port']}, using default 3306")
        port = 3306
    
    # 构建数据库URL，使用 pymysql 作为驱动
    return (
        f"mysql+pymysql://"
        f"{db_config['username']}:{db_config['password']}@"
        f"{db_config['host']}:{port}/"
        f"{db_config['database']}"
        f"?charset={db_config.get('charset', 'utf8mb4')}"
    )

def get_database_engine():
    """获取数据库引擎"""
    try:
        database_url = DatabaseManager()
        engine = create_engine(
            database_url,
            pool_size=config.get_value('database.pool_size', 5),
            max_overflow=config.get_value('database.max_overflow', 10),
            echo=config.get_value('database.echo', False)
        )
        return engine
    except Exception as e:
        logger.error(f"Failed to create database engine: {str(e)}")
        raise

# 创建数据库引擎和会话
engine = get_database_engine()
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()

def get_db():
    """获取数据库会话"""
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()